import { Injectable, HttpException, HttpStatus, Inject, forwardRef } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comment } from '../../entities/comment.entity';
import { CreateCommentDto, CommentResponseDto } from '../../dto/comment.dto';
import { Article } from '../../entities/article.entity';
import { User } from 'src/entities/user.entity';
import { UserService } from '../user/user.service';
import { SensitiveWordService } from '../sensitive/sensitive-word.service';

@Injectable()
export class CommentService {

  constructor(
    @InjectRepository(Comment)
    private commentsRepository: Repository<Comment>,
    @InjectRepository(Article)
    private articlesRepository: Repository<Article>,
    private userService: UserService,
    private sensitiveWordService: SensitiveWordService,
  ) {}

  async create(createCommentDto: CreateCommentDto, userId: number): Promise<CommentResponseDto> {
    // 检查文章是否存在
    const article = await this.articlesRepository.findOneBy({ id: createCommentDto.articleId });
    if (!article) {
      throw new HttpException('文章不存在', HttpStatus.NOT_FOUND);
    }

    // 过滤敏感词
    const filterResult = await this.sensitiveWordService.filterSensitiveWords(createCommentDto.content);

    const comment = this.commentsRepository.create({
      content: filterResult.filteredText, // 使用过滤后的内容
      articleId: createCommentDto.articleId,
      authorId: userId,
    });

    await this.commentsRepository.save(comment);
    
    return new CommentResponseDto(comment, await this.userService.findOne(userId));
  }

  async findByArticleId(articleId: number, page: number = 1, pageSize: number = 10): Promise<{ items: CommentResponseDto[], total: number, page: number, pageSize: number, hasMore: boolean }> {
    // 确保page和pageSize是有效数字
    const safePage = parseInt(page as any) || 1;
    const safePageSize = parseInt(pageSize as any) || 10;
    const skip = Math.max(0, (safePage - 1) * safePageSize);

    const query = this.commentsRepository.createQueryBuilder('comment');
    
    // 根据文章ID筛选评论
    query.andWhere('comment.articleId = :articleId', { articleId });
    
    // 只获取活跃的评论（isActive = 1）
    query.andWhere('comment.isActive = :isActive', { isActive: 1 });

    // 获取分页数据和总数
    const [comments, total] = await query
      .orderBy('comment.createdAt', 'DESC')
      .skip(skip)
      .take(safePageSize)
      .getManyAndCount();

    // 计算是否有更多数据
    const hasMore = skip + safePageSize < total;
    
    return {
      items: await Promise.all(comments.map(async comment => {
        const user= await this.userService.findOne(comment.authorId);
        // console.log('====user:', user);
        return new CommentResponseDto(comment, user);
    })),
      total,
      page: safePage,
      pageSize: safePageSize,
      hasMore
    };
  }

  async remove(id: number, userId: number): Promise<void> {
    const comment = await this.commentsRepository.findOneBy({ id, isActive: 1 });
    
    if (!comment) {
      throw new HttpException('评论不存在或已被删除', HttpStatus.NOT_FOUND);
    }

    // 检查权限
    if (comment.authorId !== userId) {
      throw new HttpException('无权删除此评论', HttpStatus.FORBIDDEN);
    }

    // 软删除：将isActive设置为0表示已删除
    await this.commentsRepository.update(id, { isActive: 0 });
  }

  /**
   * 获取所有评论（管理员）- 支持分页和筛选
   */
  async findAll(
    page: number = 1, 
    pageSize: number = 10, 
    articleId?: number,
    status?: number,
    keyword?: string
  ): Promise<{ items: CommentResponseDto[], total: number, page: number, pageSize: number, hasMore: boolean }> {
    // 确保page和pageSize是有效数字
    const safePage = parseInt(page as any) || 1;
    const safePageSize = Math.min(parseInt(pageSize as any) || 10, 50); // 限制最大页大小，避免查询过多
    const skip = Math.max(0, (safePage - 1) * safePageSize);

    const query = this.commentsRepository.createQueryBuilder('comment')
      .leftJoinAndSelect('comment.author', 'user') // 使用 JOIN 一次性获取用户信息
      .leftJoinAndSelect('comment.article', 'article'); // 同时获取文章信息

    // 根据文章ID筛选（可选）
    if (articleId) {
      query.andWhere('comment.articleId = :articleId', { articleId });
    }

    // 根据状态筛选（可选）
    if (status !== undefined && status !== null) {
      query.andWhere('comment.isActive = :status', { status });
    } else {
      // 如果没有指定状态，默认显示所有状态的评论（包括已删除的软删除记录）
      // query.andWhere('1=1'); // 默认不筛选
    }

    // 根据关键词搜索（可选）
    if (keyword) {
      query.andWhere('comment.content LIKE :keyword', { keyword: `%${keyword}%` });
    }

    try {
      // 获取分页数据和总数
      const [comments, total] = await query
        .orderBy('comment.createdAt', 'DESC')
        .skip(skip)
        .take(safePageSize)
        .getManyAndCount();

      // 计算是否有更多数据
      const hasMore = skip + safePageSize < total;
      
      return {
        items: comments.map(comment => {
          // 直接使用关联查询的结果，无需再次查询数据库
          const user = comment.author;
          const articleTitle = comment.article?.title || '未知文章';
          return new CommentResponseDto(comment, user, articleTitle);
        }),
        total,
        page: safePage,
        pageSize: safePageSize,
        hasMore
      };
    } catch (error) {
      console.error('查询评论列表时发生错误:', error);
      // 如果 JOIN 查询失败，回退到原来的方法
      return this.findAllFallback(page, pageSize, articleId, status, keyword);
    }
  }

  /**
   * 回退方法：如果 JOIN 查询失败，使用原来的方法
   */
  private async findAllFallback(
    page: number = 1, 
    pageSize: number = 10, 
    articleId?: number,
    status?: number,
    keyword?: string
  ): Promise<{ items: CommentResponseDto[], total: number, page: number, pageSize: number, hasMore: boolean }> {
    const safePage = parseInt(page as any) || 1;
    const safePageSize = Math.min(parseInt(pageSize as any) || 10, 50);
    const skip = Math.max(0, (safePage - 1) * safePageSize);

    const query = this.commentsRepository.createQueryBuilder('comment');
    
    // 根据文章ID筛选（可选）
    if (articleId) {
      query.andWhere('comment.articleId = :articleId', { articleId });
    }

    // 根据状态筛选（可选）
    if (status !== undefined && status !== null) {
      query.andWhere('comment.isActive = :status', { status });
    }

    // 根据关键词搜索（可选）
    if (keyword) {
      query.andWhere('comment.content LIKE :keyword', { keyword: `%${keyword}%` });
    }

    // 获取分页数据和总数
    const [comments, total] = await query
      .orderBy('comment.createdAt', 'DESC')
      .skip(skip)
      .take(safePageSize)
      .getManyAndCount();

    // 计算是否有更多数据
    const hasMore = skip + safePageSize < total;
    
    return {
      items: await Promise.all(comments.map(async comment => {
        const user = await this.userService.findOne(comment.authorId);
        // 获取文章标题
        let articleTitle = '未知文章';
        if (comment.articleId) {
          const article = await this.articlesRepository.findOneBy({ id: comment.articleId });
          articleTitle = article?.title || '未知文章';
        }
        return new CommentResponseDto(comment, user, articleTitle);
      })),
      total,
      page: safePage,
      pageSize: safePageSize,
      hasMore
    };
  }
  
  async removeAdmin(id: number): Promise<void> {
    const comment = await this.commentsRepository.findOneBy({ id });
    
    if (!comment) {
      throw new HttpException('评论不存在', HttpStatus.NOT_FOUND);
    }
    // 软删除：将isActive设置为0表示已删除
    await this.commentsRepository.update(id, { isActive: 0 });
  }

  async findOne(id: number): Promise<CommentResponseDto> {
    const comment = await this.commentsRepository.findOneBy({ id, isActive: 1 });
    if (!comment) {
      throw new HttpException('评论不存在或已被删除', HttpStatus.NOT_FOUND);
    }
    // 获取文章标题
    let articleTitle = '未知文章';
    if (comment.articleId) {
      const article = await this.articlesRepository.findOneBy({ id: comment.articleId });
      articleTitle = article?.title || '未知文章';
    }
    return new CommentResponseDto(comment, await this.userService.findOne(comment.authorId), articleTitle);
  }

  /**
   * 更新评论状态（管理员）
   */
  async updateStatus(id: number, isActive: number): Promise<CommentResponseDto> {
    const comment = await this.commentsRepository.findOneBy({ id });
    if (!comment) {
      throw new HttpException('评论不存在', HttpStatus.NOT_FOUND);
    }

    await this.commentsRepository.update(id, { isActive });
    
    // 获取文章标题
    let articleTitle = '未知文章';
    if (comment.articleId) {
      const article = await this.articlesRepository.findOneBy({ id: comment.articleId });
      articleTitle = article?.title || '未知文章';
    }
    
    return new CommentResponseDto(comment, await this.userService.findOne(comment.authorId), articleTitle);
  }
  
  /**
   * 更新评论内容（管理员）
   */
  async updateContentByAdmin(id: number, content: string): Promise<CommentResponseDto> {
    const comment = await this.commentsRepository.findOneBy({ id });
    if (!comment) {
      throw new HttpException('评论不存在', HttpStatus.NOT_FOUND);
    }
    
    // 过滤敏感词
    const filterResult = await this.sensitiveWordService.filterSensitiveWords(content);
    
    // 更新评论内容
    await this.commentsRepository.update(id, { 
      content: filterResult.filteredText,
      updatedAt: new Date()
    });
    
    // 重新查询更新后的评论
    const updatedComment = await this.commentsRepository.findOneBy({ id });
    if (!updatedComment) {
      throw new HttpException('评论更新失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    // 获取文章标题
    let articleTitle = '未知文章';
    if (updatedComment.articleId) {
      const article = await this.articlesRepository.findOneBy({ id: updatedComment.articleId });
      articleTitle = article?.title || '未知文章';
    }
    
    return new CommentResponseDto(updatedComment, await this.userService.findOne(updatedComment.authorId), articleTitle);
  }
  
}